"""
样式管理模块
负责模板的加载、保存、管理
"""

import os
import json
from typing import Dict, List

class StyleManager:
    def __init__(self):
        from utils.storage import get_config_path
        # 跨平台字体映射表
        self.font_map = {
            'Windows': {
                '黑体': 'SimHei',
                '微软雅黑': 'Microsoft YaHei',
                '楷体': 'KaiTi'
            },
            'Mac': {
                '黑体': 'Heiti SC',
                '微软雅黑': 'PingFang SC',
                '楷体': 'Kaiti SC'
            }
        }
        self.config_file = get_config_path()
        self.templates: Dict[str, Dict] = {}
        self.default_template: str = ""
        self.load_templates()

    def _map_font_for_platform(self, font_name: str) -> str:
        """智能字体映射"""
        system = 'Windows' if platform.system() == 'Windows' else 'Mac'
        mapped_font = self.font_map[system].get(font_name, font_name)
        return mapped_font if self._font_exists(mapped_font) else 'SimSun'

    def _font_exists(self, font_name: str) -> bool:
        """检查字体是否存在"""
        from matplotlib import font_manager
        return any(f.name == font_name for f in font_manager.fontManager.ttflist)

    def save_templates(self):
        data = {
            "templates": self.templates,
            "default_template": self.default_template
        }
        try:
            # 添加路径验证
            config_path = str(self.config_file)
            print(f"尝试保存到路径: {config_path}")
            print(f"配置文件存在: {os.path.exists(config_path)}")

            # 打印即将保存的数据
            print("保存数据:", json.dumps(data, ensure_ascii=False, indent=2))

            # save_json(data, self.config_file)
            self.save_to_file(self.config_file)

            # 保存后立即验证
            print(f"保存后文件存在: {os.path.exists(config_path)}")
            with open(config_path, 'r') as f:
                print("重新加载内容:", json.load(f))

        except Exception as e:
            print(f"模板保存失败: {str(e)}")
            raise

    def load_templates(self):
        """加载模板"""
        from utils.storage import load_json
        data = load_json(self.config_file)
        self.templates = data.get("templates", {})
        self.default_template = data.get("default_template", "")
        
        if not self.templates:
            self.templates = {
                "学术论文": {
                    "title": {
                        "font": "黑体", "size": "小二", "bold": True,
                        "alignment": "center", "space_after": 12,
                        "color": "黑色"
                    },
                    "heading1": {
                        "font": "黑体", "size": 14, "bold": True,
                        "alignment": "left", "space_before": 12,
                        "space_after": 6, "color": "黑色"
                    },
                    "heading2": {
                        "font": "楷体", "size": 12, "bold": True,
                        "alignment": "left", "space_before": 6,
                        "space_after": 6, "color": "黑色"
                    },
                    "body": {
                        "font": "宋体", "size": 12, "bold": False,
                        "alignment": "left", "first_line_indent": 7.35, # 首行缩进7.35磅
                        "line_spacing": 1.5, "color": "黑色"
                    }
                },
                "商业报告": {
                    "title": {
                        "font": "微软雅黑", "size": "小二", "bold": True,
                        "alignment": "center", "space_after": 12,
                        "color": "黑色"
                    },
                    "heading1": {
                        "font": "微软雅黑", "size": 14, "bold": True,
                        "alignment": "left", "space_before": 12,
                        "space_after": 6, "color": "黑色"
                    },
                    "heading2": {
                        "font": "微软雅黑", "size": 12, "bold": True,
                        "alignment": "left", "space_before": 6,
                        "space_after": 6, "color": "黑色"
                    },
                    "body": {
                        "font": "宋体", "size": 12, "bold": False,
                        "alignment": "left", "first_line_indent": 7.35,
                        "line_spacing": 1.5, "color": "黑色"
                    }
                }
            }
            self.default_template = "学术论文"
            self.save_templates()

    def get_template_names(self) -> List[str]:
        """获取所有模板名称"""
        return list(self.templates.keys())

    def get_template(self, name: str) -> Dict:
        """获取指定模板"""
        return self.templates.get(name, None)

    def add_template(self, name: str, template: Dict):
        """添加新模板"""
        if name not in self.templates:
            self.templates[name] = template

    def remove_template(self, name: str):
        """删除模板"""
        if name in self.templates:
            del self.templates[name]
            if self.default_template == name:
                self.default_template = ""

    def rename_template(self, old_name: str, new_name: str):
        """重命名模板"""
        if old_name in self.templates and new_name not in self.templates:
            self.templates[new_name] = self.templates.pop(old_name)
            if self.default_template == old_name:
                self.default_template = new_name

    def update_template_style(self, template_name: str, style_type: str, style: Dict):
        """更新模板中的样式"""
        if template_name in self.templates:
            self.templates[template_name][style_type] = style
            self.save_templates()

    def set_default_template(self, name: str):
        """设置默认模板"""
        if name in self.templates:
            self.default_template = name
        save_templates()

    def save_to_file(self, file_path: str):
        """保存模板到文件"""
        data = {
            "templates": self.templates,
            "default_template": self.default_template
        }
        with open(file_path, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=4)

    def load_from_file(self, file_path: str):
        """从文件加载模板"""
        if os.path.exists(file_path):
            with open(file_path, 'r', encoding='utf-8') as f:
                data = json.load(f)
                self.templates = data.get("templates", {})
                self.default_template = data.get("default_template", "")


